package com.liwei.lwmail.product.exception;

import com.liwei.common.exception.BizCodeEnume;
import com.liwei.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 集中处理指定包中的异常
 */
@Slf4j
//@ResponseBody//将异常以json数据写出
//@ControllerAdvice(basePackages = "com.liwei.lwmail.product.controller")
@RestControllerAdvice(basePackages = "com.liwei.lwmail.product.controller")
public class LwmallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)//处理的异常类型，可自定义
    public R handleValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现异常{},异常类型{}",e.getMessage(),e.getClass());

        BindingResult result = e.getBindingResult();
        Map<String,String> map = new HashMap<>();
        result.getFieldErrors().forEach((item)->{
            map.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(),BizCodeEnume.VALID_EXCEPTION.getMsg()).put("data",map);
    }

    @ExceptionHandler(value = Throwable.class)//处理任意异常
    public R handleException(Throwable throwable){
        log.error("错误：",throwable);
        return R.error(BizCodeEnume.UNKOWN_EXCEPTION.getCode(),BizCodeEnume.UNKOWN_EXCEPTION.getMsg());
    }
}
